package cn.itcast.mr.wordcount;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * Author itcast
 * Date 2021/10/15 17:21
 * Desc TODO
 */
//<KEYIN, VALUEIN, KEYOUT, VALUEOUT> 指定泛型
public class WordcountMapper extends Mapper<LongWritable/*行偏移量*/, Text/*每行内容*/,Text/*每个单词*/, IntWritable/*1*/> {
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //1.读取每行的数据
        String line = value.toString();
        //2.判空，如果每行数据不为空
        if(StringUtils.isNotEmpty(line)){
            //2.1 切割字符串，通过空格，生成数组
            String[] words = line.split(" ");
            //2.2 遍历数组中的每个值并赋值为 (单词,1)
            for (String word : words) {
                //3.将数据发送到下一步
                context.write(new Text(word),new IntWritable(1));
            }
        }
    }
}
